//
//  BPUICommonViewController.m
//  BPUIKit_Example
//
//  Created by 404 on 2020/7/30.
//  Copyright © 2020 404. All rights reserved.
//

#import "BPUICommonViewController.h"
#import "UIGestureRecognizer+BPUIKit.h"
#import "BPUICore.h"

@interface BPUICommonViewController ()<UIGestureRecognizerDelegate>

@end

@implementation BPUICommonViewController
{
    UITapGestureRecognizer *_hideKeyboardTapGestureRecognizer;
    BOOL                    _isKeyboardVisible;
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        [self didInitialize];
    }
    return self;
}

- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self didInitialize];
    }
    return self;
}

- (void)didInitialize {
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([self shouldHideKeyboardWhenTouchInView:self.view]) {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(keyboardDidShow) name:UIKeyboardDidShowNotification object:nil];
        [center addObserver:self selector:@selector(keyboardDidHide) name:UIKeyboardWillHideNotification object:nil];
        _hideKeyboardTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:NULL];
        _hideKeyboardTapGestureRecognizer.delegate = self;
        _hideKeyboardTapGestureRecognizer.enabled = NO;
        [self.view addGestureRecognizer:_hideKeyboardTapGestureRecognizer];
    }
    
    [self initSubviews];
    [self setupNavigationItems];
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // fix iOS 11 and later, shouldHideKeyboardWhenTouchInView: will not work when calling becomeFirstResponder in UINavigationController.rootViewController.viewDidLoad
    if (@available(iOS 11.0, *)) {
        if (_hideKeyboardTapGestureRecognizer && _isKeyboardVisible) {
            self.hideKeyboardTapGestureRecognizer.enabled = YES;
        }
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self layoutEmptyView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

#pragma mark - 空列表视图 QMUIEmptyView

@synthesize emptyView = _emptyView;

- (BPUIEmptyView *)emptyView {
    if (!_emptyView && self.isViewLoaded) {
        _emptyView = [[BPUIEmptyView alloc] initWithFrame:self.view.bounds];
    }
    return _emptyView;
}

- (void)showEmptyView {
    [self.view addSubview:self.emptyView];
}

- (void)hideEmptyView {
    [_emptyView removeFromSuperview];
}

- (BOOL)isEmptyViewShowing {
    return _emptyView && _emptyView.superview;
}

- (void)showEmptyViewWithLoading {
    [self showEmptyView];
    [self.emptyView setImage:nil];
    [self.emptyView setLoadingViewHidden:NO];
    [self.emptyView setTextLabelText:nil];
    [self.emptyView setDetailTextLabelText:nil];
    [self.emptyView setActionButtonTitle:nil];
}

- (void)showEmptyViewWithText:(NSString *)text
                   detailText:(NSString *)detailText
                  buttonTitle:(NSString *)buttonTitle
                 buttonAction:(SEL)action {
    [self showEmptyViewWithLoading:NO image:nil text:text detailText:detailText buttonTitle:buttonTitle buttonAction:action];
}

- (void)showEmptyViewWithImage:(UIImage *)image
                          text:(NSString *)text
                    detailText:(NSString *)detailText
                   buttonTitle:(NSString *)buttonTitle
                  buttonAction:(SEL)action {
    [self showEmptyViewWithLoading:NO image:image text:text detailText:detailText buttonTitle:buttonTitle buttonAction:action];
}

- (void)showEmptyViewWithLoading:(BOOL)showLoading
                           image:(UIImage *)image
                            text:(NSString *)text
                      detailText:(NSString *)detailText
                     buttonTitle:(NSString *)buttonTitle
                    buttonAction:(SEL)action {
    [self showEmptyView];
    [self.emptyView setLoadingViewHidden:!showLoading];
    [self.emptyView setImage:image];
    [self.emptyView setTextLabelText:text];
    [self.emptyView setDetailTextLabelText:detailText];
    [self.emptyView setActionButtonTitle:buttonTitle];
    [self.emptyView.actionButton removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
    [self.emptyView.actionButton addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
}

- (BOOL)layoutEmptyView {
    if (_emptyView) {
        // 由于为self.emptyView设置frame时会调用到self.view，为了避免导致viewDidLoad提前触发，这里需要判断一下self.view是否已经被初始化
        BOOL viewDidLoad = self.emptyView.superview && [self isViewLoaded];
        if (viewDidLoad) {
            CGSize newEmptyViewSize = self.emptyView.superview.bounds.size;
            CGSize oldEmptyViewSize = self.emptyView.frame.size;
            if (!CGSizeEqualToSize(newEmptyViewSize, oldEmptyViewSize)) {
                self.emptyView.frame = CGRectMake(CGRectGetMinX(self.emptyView.frame), CGRectGetMinY(self.emptyView.frame), newEmptyViewSize.width, newEmptyViewSize.height);
            }
            return YES;
        }
    }
    
    return NO;
}


#pragma mark - keyboard

-(void)keyboardDidShow{
    _isKeyboardVisible = YES;
    self.hideKeyboardTapGestureRecognizer.enabled = YES;
}

-(void)keyboardDidHide{
    _isKeyboardVisible = NO;
    self.hideKeyboardTapGestureRecognizer.enabled = NO;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer != self.hideKeyboardTapGestureRecognizer) {
        return YES;
    }
    
    if (!self.isKeyboardVisible) {
        return NO;
    }
    
    UIView *targetView = gestureRecognizer.targetView;
    
    // 点击了本身就是输入框的 view，就不要降下键盘了
    if ([targetView isKindOfClass:[UITextField class]] || [targetView isKindOfClass:[UITextView class]]) {
        return NO;
    }
    
    if ([self shouldHideKeyboardWhenTouchInView:targetView]) {
        [self.view endEditing:YES];
    }
    return NO;
}

@end

@implementation BPUICommonViewController (BPUIKitSubclassingHooks)

- (void)initSubviews {
    // 子类重写
}

- (void)setupNavigationItems {
    // 子类重写
}

@end

@implementation BPUICommonViewController (BPUIKitKeyboard)

- (UITapGestureRecognizer *)hideKeyboardTapGestureRecognizer{
    return _hideKeyboardTapGestureRecognizer;
}

- (BOOL)shouldHideKeyboardWhenTouchInView:(UIView *)view{
    return NO;
}

- (BOOL)isKeyboardVisible{
    return _isKeyboardVisible;
}

@end
